package com.company.management.utils;


import com.company.management.config.CustomConfig;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件上传工具类
 */
public class FileUploadUtils {

    public static final String uploadFile(MultipartFile file, String uuid) throws Exception {
        // 本地文件保存位置
        String path = getPath(file);
        File uploadDir = new File(path);
        if (!uploadDir.exists()) {
            boolean mkdirs = uploadDir.mkdirs();
            System.out.println(mkdirs);
        }
        String originalFilename = file.getOriginalFilename();
        //文件扩展名
        String extname = originalFilename.substring(originalFilename.lastIndexOf("."));
        //随机名+文件扩展名
        String newFileName = uuid.concat(extname);
        Path systemPath = Paths.get(path, newFileName);
        Files.write(systemPath, file.getBytes());
        return uploadDir.getAbsolutePath();
    }

    private static String getPath(MultipartFile file) {
        StringBuilder sb = new StringBuilder(CustomConfig.getPath());
        sb.append(File.separator).append(DateUtils.datePath());
        return sb.toString();
    }

    /**
     * 下载文件名重新编码
     *
     * @param response     响应对象
     * @param realFileName 真实文件名
     * @return
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);

        response.setHeader("Content-disposition", contentDispositionValue.toString());
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }

    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os       输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            IOUtils.close(os);
            IOUtils.close(fis);
        }
    }
}